class_name Hand
extends HBoxContainer

@export var char_stats: CharacterStats
@export var player_handler:PlayerHandler
@onready var card_ui := preload("res://scene/card_UI/card_ui.tscn")

var cards_played_this_turn := 0

func _ready() -> void:
	Events.card_played.connect(_on_card_played)

func add_card(card: Card) -> void:
	var new_card_ui :CardUI= card_ui.instantiate()
	add_child(new_card_ui)
	new_card_ui.reqarent_requested.connect(_on_card_ui_reparent_requested)
	new_card_ui.card = card
	new_card_ui.parent = self
	player_handler.player_mana_changed.connect(new_card_ui.on_player_mana_changed)
	new_card_ui.on_player_mana_changed(player_handler.cur_mana)
	
func discard_hand() -> void:
	for card_ui in get_children():
		discard_card(card_ui)
	
func discard_card(card_ui: CardUI) -> void:
	card_ui.queue_free()

func disable_hand() -> void:
	for card_ui in get_children():
		card_ui.disabled = true
	
func _on_card_played(_card: Card) -> void:
	cards_played_this_turn += 1

func _on_card_ui_reparent_requested(child: CardUI) -> void:
	child.reparent(self)
	var new_index := clampi(child.original_index - cards_played_this_turn, 0, get_child_count())
	move_child.call_deferred(child, new_index)
